package com.imooc.distributedemo.resume;

/**
 * 交替打印基数/偶数--交替打印奇偶数
 */
public class SupersedePrint {
    // 定义一个object锁对象
    private static final Object lock = new Object();
    // 定一个全局变量，控制奇偶判断
    private static int number = 1;
    // 定一个最大循环数
    private static final int MAX_NUMBER = 100;

    public static void main(String[] args) {
        Thread oddThread = new Thread(new OddPrinter());
        Thread evenThread = new Thread(new EvenPrinter());

        oddThread.start();
        evenThread.start();
    }

    static class OddPrinter implements Runnable {

        @Override
        public void run() {
            while (number <= MAX_NUMBER){
                synchronized (lock){
                    if(number %2 ==0){
                        try{
                            lock.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace(); // 简单这么写，业务系统禁止
                        }
                    }else{
                        // 打印奇数
                        System.out.println(Thread.currentThread().getName()+"--print--"+number);
                        number++;
                        lock.notify();
                    }
                }
            }
        }
    }

    static class EvenPrinter implements Runnable {

        @Override
        public void run() {
            while (number <= MAX_NUMBER){
                synchronized (lock){
                    if(number %2 !=0){
                        try{
                            lock.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace(); // 简单这么写，业务系统禁止
                        }
                    }else{
                        // 打印偶数
                        System.out.println(Thread.currentThread().getName()+"--print--"+number);
                        number++;
                        lock.notify();
                    }
                }
            }
        }
    }
}
